<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>购物车</title>

    <link rel="stylesheet" href="/css/index.css">
    <link rel="stylesheet" href="/css/cart.css">
    <link rel="stylesheet" href="/bootstrap/css/bootstrap.css">
</head>

<body>

<div class="dingbu">
    <div class="denglu-font top">
         <a href="/" id="dingbuhome"><img src="/images/logo.jpg"></a>

        <div id="so" style="position: relative; left: 350px;top:8px;width: 100px; float: left;" class="top">
            <div class="input-group">
                <input type="text" class="form-control" id="searchText" style="width: 380px;">
                <span class="input-group-addon" id="search" onclick="search()"><i class="glyphicon glyphicon-search"
                                                                                  style="color: #0055aa;"> <span>搜索
                                </span></i></span>
            </div>
        </div>
        <div class="denglu-font2 top">
            <a href="/" id="wants">发布求购</a>
            <a href="/" id="cart">我的购物车</a>
            <a href="#" id="release">发布商品</a>
            <a href="#" id="uname"></a>
            <a href="login" id="login_logout">登录</a>

        </div>
    </div>
</div>

<!--<div>-->
<!--    <h2 style="position: relative; top: 20px; left: 20px">购物车</h2>-->
<!--</div>-->

<!--    <div>-->

<!--    </div>-->

<div class="shopping-car-container">
    <div class="car-headers-menu">
        <div class="row">
            <div class="col-md-1 car-menu">
                <label><input type="checkbox" id="check-goods-all"/><span id="checkAll">全选</span></label>
            </div>
            <div class="col-md-3 car-menu">商品名称</div>
            <div class="col-md-3 car-menu">商品新旧程度</div>
            <div class="col-md-1 car-menu">单价</div>
            <div class="col-md-1 car-menu">数量</div>
            <div class="col-md-1 car-menu">金额</div>
            <div class="col-md-2 car-menu">操作</div>
        </div>
    </div>
    <!--        <div class="goods-content">-->
    <!--            &lt;!&ndash; <div class="goods-item">-->
    <!--                <div class="panel panel-default">-->
    <!--                    <div class="panel-body">-->
    <!--                        <div class="col-md-1 car-goods-info">-->
    <!--                            <label><input type="checkbox" class="goods-list-item" /></label>-->
    <!--                        </div>-->
    <!--                        <div class="col-md-3 car-goods-info goods-image-column">-->
    <!--                            <img class="goods-image" src=" item.imgUrl + " style="width: 100px; height: 100px;" />-->
    <!--                            <span id="goods-info">-->
    <!--                                很好吃的酸辣粉-->
    <!--                            </span>-->
    <!--                        </div>-->
    <!--                        <div class="col-md-3 car-goods-info goods-params"> 酸辣粉 </div>-->
    <!--                        <div class="col-md-1 car-goods-info goods-price"><span>￥</span><span class="single-price">-->
    <!--                                199 </span></div>-->
    <!--                        <div class="col-md-1 car-goods-info goods-counts">-->
    <!--                            <div class="input-group">-->
    <!--                                <div class="input-group-btn">-->
    <!--                                    <button type="button" class="btn btn-default car-decrease">-</button>-->
    <!--                                </div>-->
    <!--                                <input type="text" class="form-control goods-count" value="1">-->
    <!--                                <div class="input-group-btn">-->
    <!--                                    <button type="button" class="btn btn-default car-add">+</button>-->
    <!--                                </div>-->
    <!--                            </div>-->
    <!--                        </div>-->
    <!--                        <div class="col-md-1 car-goods-info goods-money-count"><span>￥</span><span class="single-total">-->
    <!--                                199</span></div>-->
    <!--                        <div class="col-md-2 car-goods-info goods-operate">-->
    <!--                            <button type="button" class="btn btn-danger item-delete">删除</button>-->
    <!--                        </div>-->
    <!--                    </div>-->
    <!--                </div>-->
    <!--            </div>&ndash;&gt;-->

    <div th:each="cartOrder:${cart.orderList}" th:object="${cartOrder}" class="goods-item">
        <div class="panel panel-default" th:id="${cartOrder.item.id}">
            <div class="panel-body">
                <div class="col-md-1 car-goods-info">
                    <label><input type="checkbox" class="goods-list-item"/></label>
                </div>
                <div class="col-md-3 car-goods-info goods-image-column">
                    <img class="goods-image" th:src="${cartOrder.item.image}" style="width: 100px; height: 100px;"/>
                    <span id="goods-info" th:text="${cartOrder.item.itemName}">
                            </span>
                </div>
                <div class="col-md-3 car-goods-info goods-params" th:text="${cartOrder.item.level}"></div>
                <div class="col-md-1 car-goods-info goods-price">
                    <span>￥</span>
                    <span class="single-price" th:text="${cartOrder.item.price}">
                            </span>
                </div>
                <div class="col-md-1 car-goods-info goods-counts">
                    <div class="input-group">
                        <div class="input-group-btn">
                            <button type="button" class="btn btn-default car-decrease">-</button>
                        </div>
                        <input type="text" class="form-control goods-count" th:value="${cartOrder.itemCount}"
                               th:max="${cartOrder.item.count}" disabled>
                        <div class="input-group-btn">
                            <button type="button" class="btn btn-default car-add">+</button>
                        </div>
                    </div>
                </div>
                <div class="col-md-1 car-goods-info goods-money-count"><span>￥</span><span class="single-total"
                                                                                           th:text="${cartOrder.item.price * cartOrder.itemCount}"> </span>
                </div>
                <div class="col-md-2 car-goods-info goods-operate">
                    <button type="button" class="btn btn-danger item-delete">删除</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="panel panel-default">
    <div class="panel-body bottom-menu-include">
        <div class="col-md-1 check-all-bottom bottom-menu">
            <label>
                <input type="checkbox" id="checked-all-bottom"/>
                <span id="checkAllBottom">全选</span>
            </label>
        </div>
        <div class="col-md-1 bottom-menu">
                    <span id="deleteMulty">
                        删除
                    </span>
        </div>
        <div class="col-md-6 bottom-menu">

        </div>
        <div class="col-md-2 bottom-menu">
            <span>已选商品 <span id="selectGoodsCount">0</span> 件</span>
        </div>
        <div class="col-md-1 bottom-menu">
            <span>合计：<span id="selectGoodsMoney">0.00</span></span>
        </div>
        <div class="col-md-1 bottom-menu submitData submitDis" style="position: relative; top: 0px;" id="submit">
            结算
        </div>
    </div>
</div>
<!--删除确认弹框-->
<div class="modal fade" tabindex="-1" role="dialog" id="deleteItemTip" aria-labelledby="gridSystemModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="gridSystemModalLabel1">提示</h4>
            </div>
            <div class="modal-body">
                确认删除此商品？
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary deleteSure">确定</button>
            </div>
        </div>
    </div>
</div>
<!--是否勾选商品提示-->
<div class="modal fade" tabindex="-1" role="dialog" id="selectItemTip" aria-labelledby="gridSystemModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="gridSystemModalLabel2">提示</h4>
            </div>
            <div class="modal-body">
                请选择要删除的商品！
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>
<!--批量删除商品-->
<div class="modal fade" tabindex="-1" role="dialog" id="deleteMultyTip" aria-labelledby="gridSystemModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="gridSystemModalLabel3">提示</h4>
            </div>
            <div class="modal-body">
                确认删除选择的商品！
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary deleteMultySure">确定</button>
            </div>
        </div>
    </div>
</div>

<!--请选择购买商品的弹窗-->
<div class="modal fade" tabindex="-1" role="dialog" id="selectBuyTip" aria-labelledby="gridSystemModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="gridSystemModalLabel4">提示</h4>
            </div>
            <div class="modal-body">
                请选择要购买的商品！
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>
<!--购买商品弹窗-->
<div class="modal fade" tabindex="-1" role="dialog" id="buyitems" aria-labelledby="gridSystemModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="gridSystemModalLabel">提示</h4>
            </div>
            <div class="modal-body">
                确认购买？
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary buyitems" id="buySure">确定</button>
            </div>
        </div>
    </div>
</div>
</div>
<script src="/jquery/jquery.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/layer/layer.js"></script>
<script th:inline="javascript">
    $('#login_logout').click(function () {
        localStorage.clear()
    })
    function search() {
        console.log($('#searchText').val())
        var data = $('#searchText').val()
        location.assign('/search?keyword=' + data)
    }

    var deleteGoods = null
    var userId = localStorage.getItem('userId')

    var cartId = [[${cart.id}]]
    var items = []
    buyitem = null

    function ShoppingCarObserver(elInput, isAdd) {
        this.elInput = elInput
        this.parents = this.elInput.parents('.goods-item')
        this.itemId = this.elInput.parents('.panel-default').attr('id')
        this.count = parseInt(this.elInput.val())
        this.isAdd = isAdd
        this.singlePrice = parseFloat(this.parents.find('.single-price').text())
        this.computeGoodsMoney = function () {
            var moneyCount = this.count * this.singlePrice
            var singleTotalEl = this.parents.find('.single-total')
            console.log(moneyCount)
            singleTotalEl.empty().append(moneyCount.toFixed(2))
        }
        this.showCount = function () {
            var isChecked = this.parents.find('.goods-list-item')[0].checked
            var GoodsTotalMoney = parseFloat($('#selectGoodsMoney').text())
            var goodsTotalCount = parseInt($('#selectGoodsCount').text())
            if (this.elInput) {
                if (this.isAdd) {
                    ++this.count
                    if (isChecked) {
                        $('#selectGoodsMoney').empty().append((GoodsTotalMoney + this.singlePrice).toFixed(2))
                        $('#selectGoodsCount').empty().append(goodsTotalCount + 1)
                    }
                } else {
                    if (parseInt(this.count) <= 1) {
                        return
                    } else {
                        --this.count
                        if (isChecked) {
                            $('#selectGoodsMoney').empty().append((GoodsTotalMoney - this.singlePrice).toFixed(2))
                            $('#selectGoodsCount').empty().append(goodsTotalCount - 1)
                        }
                    }
                }
                $.ajax({
                    url: '/api/cart/changevalue?cartId=' + cartId + '&itemId=' + this.itemId + '&count=' + this.count,
                    data: '',
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    traditional: true
                })
                this.elInput.val(this.count)
            }
        }
        this.checkIsAll = function () {
            var checkLen = $('.goods-list-item:checked').length
            if (checkLen > 0) {
                $('.submitData').removeClass('submitDis')
            } else {
                $('.submitData').addClass('submitDis')
            }
            if ($('.goods-item').length === checkLen) {
                $('#checked-all-bottom, #check-goods-all').prop('checked', true)
            } else {
                $('#checked-all-bottom, #check-goods-all').prop('checked', false)
            }
        }
        this.checkedChange = function (isChecked) {
            if (isChecked === undefined) {
                var isChecked = this.parents.find('.goods-list-item')[0].checked
            }
            var itemTotalMoney = parseFloat(this.parents.find('.single-total').text())
            var GoodsTotalMoney = parseFloat($('#selectGoodsMoney').text())
            var itemCount = parseInt(this.parents.find('.goods-count').val())
            var goodsTotalCount = parseInt($('#selectGoodsCount').text())
            if (isChecked) {
                $('#selectGoodsMoney').empty().append((itemTotalMoney + GoodsTotalMoney).toFixed(2))
                $('#selectGoodsCount').empty().append(itemCount + goodsTotalCount)
            } else {
                if (GoodsTotalMoney - itemTotalMoney === 0) {
                    $('#selectGoodsMoney').empty().append('0.00')
                    if (!$('.submitData').hasClass('submitDis')) {
                        $('.submitData').addClass('submitDis')
                    }
                } else {
                    $('#selectGoodsMoney').empty().append((GoodsTotalMoney - itemTotalMoney).toFixed(2))
                }
                $('#selectGoodsCount').empty().append((goodsTotalCount - itemCount).toFixed(2))
            }
        }
        this.deleteGoods = function () {
            var isChecked = this.parents.find('.goods-list-item')[0].checked
            if (isChecked) {
                this.checkedChange(false)
            }
            var itemId = $(this.parents.find('.panel-default')[0]).attr('id')
            $.ajax({
                url: '/api/cart/remove?userId=' + userId + '&itemId=' + itemId,
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: '',
                traditional: true,
                success: function (data) {
                    if (data.code == 0) {
                        layer.msg('删除成功')
                        location.reload()
                    } else {
                        layer.msg(data.msg)
                    }
                }
            })
            this.parents.remove()
            this.checkOptions()
        }
        this.checkOptions = function () {
            if ($('#check-goods-all')[0].checked) {
                if ($('.goods-list-item').length <= 0) {
                    $('#checked-all-bottom, #check-goods-all').prop('checked', false)
                }
            }
        }
        this.buygoods = function () {
            var isChecked = this.parents.find('.goods-list-item')[0].checked
            if (isChecked) {
                this.checkedChange(false)
            }
            var itemId = $(this.parents.find('.panel-default')[0]).attr('id')
            var value = $(this.parents.find('.goods-count')[0]).val()
            // var value = 10
            buyitems += '{"itemId":' + itemId + ',"value":' + value + '}'
            items[items.length] = {'itemId': itemId, 'value': value}
            this.parents.remove()
            this.checkOptions()
        }
    }

    function checkedAll(_this) {
        if ($('.goods-item').length <= 0) {
            $('.submitData').addClass('submitDis')
        } else {
            $('.submitData').removeClass('submitDis')
        }
        for (var i = 0; i < $('.goods-item').length; i++) {
            var elInput = $('.goods-item').eq(i).find('.goods-list-item')
            var isChecked = $('.goods-item').eq(i).find('.goods-list-item')[0].checked
            var checkAllEvent = new ShoppingCarObserver(elInput, null)
            if (_this.checked) {
                if (!isChecked) {
                    elInput.prop('checked', true)
                    checkAllEvent.checkedChange(true)
                }
            } else {
                if (!$('.submitData').hasClass('submitDis')) {
                    $('.submitData').addClass('submitDis')
                }
                if (isChecked) {
                    elInput.prop('checked', false)
                    checkAllEvent.checkedChange(false)
                }
            }
        }
    }

    $('#check-goods-all').on('change', function () {
        if (this.checked) {
            $('#checked-all-bottom').prop('checked', true)
        } else {
            $('#checked-all-bottom').prop('checked', false)
        }
        checkedAll(this)
    })
    $('#checked-all-bottom').on('change', function () {
        if (this.checked) {
            $('#check-goods-all').prop('checked', true)
        } else {
            $('#check-goods-all').prop('checked', false)
        }
        checkedAll(this)
    })
    $('.goods-list-item').on('change', function () {
        var tmpCheckEl = $(this)
        var checkEvent = new ShoppingCarObserver(tmpCheckEl, null)
        checkEvent.checkedChange()
        checkEvent.checkIsAll()
    })

    $('.car-decrease').on('click', function () {
        var goodsInput = $(this).parents('.input-group').find('.goods-count')
        var decreaseCount = new ShoppingCarObserver(goodsInput, false)
        decreaseCount.showCount()
        decreaseCount.computeGoodsMoney()
    })
    $('.car-add').on('click', function () {
        var goodsInput = $(this).parents('.input-group').find('.goods-count')
        var addCount = new ShoppingCarObserver(goodsInput, true)
        addCount.showCount()
        addCount.computeGoodsMoney()
    })
    $('.item-delete').on('click', function () {
        var goodsInput = $(this).parents('.goods-item').find('.goods-list-item')
        deleteGoods = new ShoppingCarObserver(goodsInput, null)
        $('#deleteItemTip').modal('show')
    })
    $('.deleteSure').on('click', function () {
        if (deleteGoods !== null) {
            deleteGoods.deleteGoods()
        }
        $('#deleteItemTip').modal('hide')
    })
    $('#deleteMulty').on('click', function () {
        if ($('.goods-list-item:checked').length <= 0) {
            $('#selectItemTip').modal('show')
        } else {
            $('#deleteMultyTip').modal('show')
        }
    })
    $('.deleteMultySure').on('click', function () {
        for (var i = 0; i < $('.goods-list-item:checked').length; i++) {
            var multyDelete = new ShoppingCarObserver($('.goods-list-item:checked').eq(i), null)
            multyDelete.deleteGoods()
            i--
        }
        multyDelete.checkOptions()
        $('#deleteMultyTip').modal('hide')
    })

    $('#submit').on('click', function () {
        if ($('.goods-list-item:checked').length <= 0) {
            $('#selectBuyTip').modal('show')
        } else {
            var totalCount = $('#selectGoodsCount').text()
            var totalPrice = $('#selectGoodsMoney').text()
            $('#buyitems').find('.modal-body').text('共选' + totalCount + '件商品，共计' + totalPrice + '元')
            $('#buyitems').modal('show')
        }
    })

    $('#buySure').on('click', function () {
        buyitems = '['
        for (var i = 0; i < $('.goods-list-item:checked').length; i++) {
            var buy = new ShoppingCarObserver($('.goods-list-item:checked').eq(i), null)
            buy.buygoods()
            i--
            if ($('.goods-list-item:checked').length >= 1) {
                buyitems += ','
            }
        }
        buyitems += ']'
        console.log(JSON.stringify(items))
        if (userId == null || userId == '') {
            layer.msg('请登陆后再购买商品！')
            return
        }
        $.ajax({
            url: '/api/order/addcart?userId=' + userId,
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({'items': items}),
            traditional: true,
            success: function (data) {
                if (data.code == 0) {
                    layer.msg('购买成功！')
                    location.reload()
                } else {
                    layer.msg(data.msg)
                }
            }
        })
        $('#buyitems').modal('hide')
    })

    $(function () {
        load_data()
    })

    //设置顶部栏的登录/退出按钮和用户名显示

    function load_data() {
        var theme = localStorage.getItem('username')
        var userId = localStorage.getItem('userId')

        console.log(localStorage.getItem('username'))
        console.log(localStorage.getItem('userId'))
        if (theme == null || theme == '') {
            $('#login_logout').text('登录')
            $('#uname').text('')
            $('#wants').hide();
            $("release").hide()
            $('#cart').hide()
        } else {
            $('#login_logout').text('退出')
            $('#login_logout').attr('href', '/logout')
            $('#uname').text(theme)
            $('#wants').show()
            $('#wants').attr('href', '/api/wants/release?userId=' + userId)
            $('#release').show();
            $('#release').attr('href', '/release')
            $('#cart').show()
            $('#cart').attr('href', '/api/cart/all?userId=' + userId)
            $('#uname').attr('href', '/api/user/info?userId=' + userId)
        }
    }

    function checkValue(count) {
        if (count == null || count == '' || count <= 0) {
            return false
        } else {
            // $(e).val(Math.trunc(count));
            return true
        }
    }


</script>
</body>

</html>
